<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="租户名称"
        style="width: 200px"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-select
        v-model="listQuery.status"
        placeholder="租户状态"
        clearable
        style="width: 120px"
      >
        <el-option label="启用" value="active" />
        <el-option label="禁用" value="inactive" />
        <el-option label="试用" value="trial" />
      </el-select>
      <el-button
        v-has-perm="'view:tenant'"
        class="filter-item"
        type="primary"
        @click="handleFilter"
      >
        查询
      </el-button>
      <el-button type="info" @click="getList">刷新</el-button>
      <el-button
        v-has-perm="'add:tenant'"
        v-test-account
        class="filter-item"
        type="success"
        @click="handleCreate"
      >
        新增
      </el-button>
    </div>

    <!-- 调试信息 -->
    <div
      style="
        margin: 10px 0;
        padding: 10px;
        background: #f5f5f5;
        border-radius: 4px;
      "
    >
      <p><strong>调试信息:</strong></p>
      <p>Loading状态: {{ listLoading }}</p>
      <p>租户数量: {{ list.length }}</p>
      <p>总数: {{ total }}</p>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" align="center" width="80" />
      <el-table-column prop="name" label="租户名称" min-width="150" />
      <el-table-column prop="code" label="租户标识" min-width="120" />
      <el-table-column prop="app_id" label="微信AppID" min-width="150" />
      <el-table-column prop="admin_name" label="管理员" width="120" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag v-if="row.status === 'active'" type="success">启用</el-tag>
          <el-tag v-else-if="row.status === 'inactive'" type="danger"
            >禁用</el-tag
          >
          <el-tag v-else-if="row.status === 'trial'" type="warning"
            >试用</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="expire_date" label="到期日期" width="180" />
      <el-table-column prop="created_at" label="创建时间" width="180" />
      <el-table-column label="操作" align="center" width="250">
        <template #default="{ row }">
          <el-button
            v-has-perm="'edit:tenant'"
            v-test-account
            size="small"
            type="primary"
            @click="handleUpdate(row)"
          >
            编辑
          </el-button>
          <el-button
            v-has-perm="'edit:tenant'"
            v-test-account
            size="small"
            :type="row.status === 'active' ? 'danger' : 'success'"
            @click="handleToggleStatus(row)"
          >
            {{ row.status === "active" ? "禁用" : "启用" }}
          </el-button>
          <el-button
            v-has-perm="'delete:tenant'"
            v-test-account
            size="small"
            type="danger"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="total > 0"
      :total="total"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="listQuery.limit"
      v-model:current-page="listQuery.page"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 租户编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
      <el-form
        ref="dataForm"
        :model="tempTenant"
        :rules="rules"
        label-position="left"
        label-width="120px"
      >
        <!-- 基础信息 -->
        <el-form-item label="租户名称" prop="name">
          <el-input v-model="tempTenant.name" placeholder="请输入租户名称" />
        </el-form-item>
        <el-form-item label="租户标识" prop="code">
          <el-input
            v-model="tempTenant.code"
            placeholder="请输入租户标识，如：tenant1"
          />
        </el-form-item>

        <!-- 微信配置 -->
        <el-form-item label="微信AppID" prop="app_id">
          <el-input
            v-model="tempTenant.app_id"
            placeholder="请输入微信小程序AppID"
          />
        </el-form-item>

        <!-- 管理员信息 -->
        <el-form-item label="管理员账号" prop="admin_name">
          <el-input
            v-model="tempTenant.admin_name"
            placeholder="请输入管理员账号"
          />
        </el-form-item>
        <el-form-item label="租户状态" prop="status">
          <el-select
            v-model="tempTenant.status"
            placeholder="请选择租户状态"
            style="width: 100%"
          >
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
            <el-option label="试用" value="trial" />
          </el-select>
        </el-form-item>
        <el-form-item label="到期日期" prop="expire_date">
          <el-date-picker
            v-model="tempTenant.expire_date"
            type="date"
            placeholder="请选择到期日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="tempTenant.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button v-test-account type="primary" @click="submitForm"
            >确 定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/store/user";
import {
  getTenantList as apiGetTenantList,
  createTenant as apiCreateTenant,
  updateTenant as apiUpdateTenant,
  updateTenantStatus as apiUpdateTenantStatus,
  deleteTenant as apiDeleteTenant,
} from "@/api/tenant";

const userStore = useUserStore();

const list = ref([]);
const total = ref(0);
const listLoading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref("");
const dataForm = ref(null);
const isCreate = ref(false);

const listQuery = reactive({
  page: 1,
  limit: 10,
  name: "",
  status: "",
});

const tempTenant = reactive({
  id: undefined,
  name: "", // 租户名称
  app_id: "", // 微信小程序 AppID
  code: "", // 租户标识
  admin_name: "", // 管理员账号
  status: "active", // 状态
  expire_date: "", // 到期日期
  remark: "", // 备注
});

const rules = {
  // 基础字段验证
  name: [{ required: true, message: "请输入租户名称", trigger: "blur" }],
  app_id: [{ required: true, message: "请输入微信AppID", trigger: "blur" }],
  code: [{ required: true, message: "请输入租户标识", trigger: "blur" }],

  // 管理员字段验证
  admin_name: [
    { required: true, message: "请输入管理员账号", trigger: "blur" },
  ],

  // 状态和日期验证
  status: [{ required: true, message: "请选择租户状态", trigger: "change" }],
  expire_date: [
    { required: true, message: "请选择到期日期", trigger: "change" },
  ],
};

// 获取租户列表
const getList = async () => {
  listLoading.value = true;
  try {
    const params = {
      page: listQuery.page,
      limit: listQuery.limit,
      name: listQuery.name,
      status: listQuery.status,
    };
    const response = await apiGetTenantList(params);
    console.log("租户列表响应:", response);

    if (response.code === 0) {
      // 检查数据格式并处理
      if (Array.isArray(response.data)) {
        // 如果直接返回数组
        list.value = [...response.data];
        total.value = response.data.length;
      } else if (response.data && response.data.items) {
        // 如果返回包含items的对象
        list.value = [...response.data.items];
        total.value = response.data.total || 0;
      } else {
        console.warn("未知的租户数据格式:", response.data);
        list.value = [];
        total.value = 0;
      }

      console.log(`租户列表加载成功: ${list.value.length} 条记录`);
    } else {
      ElMessage.error(response.message || "获取租户列表失败");
    }
  } catch (error) {
    console.error("获取租户列表失败", error);
    ElMessage.error("获取租户列表失败");
  } finally {
    listLoading.value = false;
  }
};

// 筛选
const handleFilter = () => {
  listQuery.page = 1;
  getList();
};

// 每页数量变化
const handleSizeChange = (val) => {
  listQuery.limit = val;
  getList();
};

// 页码变化
const handleCurrentChange = (val) => {
  listQuery.page = val;
  getList();
};

// 创建租户
const handleCreate = () => {
  dialogTitle.value = "创建租户";
  dialogVisible.value = true;
  isCreate.value = true;

  // 重置表单
  nextTick(() => {
    if (dataForm.value) {
      dataForm.value.resetFields();
    }

    Object.assign(tempTenant, {
      id: undefined,
      name: "", // 租户名称
      app_id: "", // 微信小程序 AppID
      code: "", // 租户标识
      admin_name: "", // 管理员账号
      status: "active", // 状态
      expire_date: "", // 到期日期
      remark: "", // 备注
    });
  });
};

// 更新租户
const handleUpdate = (row) => {
  dialogTitle.value = "编辑租户";
  dialogVisible.value = true;
  isCreate.value = false;

  // 重置表单并填充数据
  nextTick(() => {
    if (dataForm.value) {
      dataForm.value.resetFields();
    }

    Object.assign(tempTenant, { ...row, admin_password: "" });
  });
};

// 切换租户状态
const handleToggleStatus = async (row) => {
  const newStatus = row.status === "active" ? "inactive" : "active";
  const statusText = newStatus === "active" ? "启用" : "禁用";

  try {
    await ElMessageBox.confirm(`确定要${statusText}该租户吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await apiUpdateTenantStatus(row.id, newStatus);
    if (response.code === 0) {
      row.status = newStatus;
      ElMessage.success(`${statusText}成功`);
    } else {
      ElMessage.error(response.message || `${statusText}失败`);
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error(`${statusText}租户失败:`, error);
      ElMessage.error(`${statusText}失败`);
    }
  }
};

// 删除租户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm("确定要删除该租户吗？删除后不可恢复！", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await apiDeleteTenant(row.id);
    if (response.code === 0) {
      ElMessage.success("删除成功");
      getList(); // 重新获取列表
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除租户失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 提交表单
const submitForm = async () => {
  if (!dataForm.value) return;

  try {
    await dataForm.value.validate();

    // 准备提交数据
    const submitData = { ...tempTenant };

    // 移除前端专用字段
    delete submitData.id;

    // 处理日期格式
    if (submitData.expire_date) {
      if (submitData.expire_date instanceof Date) {
        submitData.expire_date = submitData.expire_date
          .toISOString()
          .split("T")[0];
      }
    }

    console.log("提交的租户数据:", submitData);

    let response;
    if (tempTenant.id === undefined) {
      // 新增租户
      console.log("创建租户，发送数据:", submitData);
      response = await apiCreateTenant(submitData);
    } else {
      // 更新租户
      console.log("更新租户，发送数据:", submitData);
      response = await apiUpdateTenant(tempTenant.id, submitData);
    }

    console.log("租户操作响应:", response);

    if (response.code === 0) {
      ElMessage.success(tempTenant.id === undefined ? "创建成功" : "更新成功");
      dialogVisible.value = false;
      getList(); // 重新获取列表
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("提交表单失败:", error);
    ElMessage.error("操作失败");
  }
};

// 获取数据
onMounted(() => {
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 20px;
}

.filter-item {
  margin-right: 10px;
}

.dialog-footer {
  text-align: right;
}
</style>
